<template>
  <view>
    <view class="goods-list">
      <view v-for="(item, i) in goodsList" :key="i" @click="gotoDetail(item)">
        <my-goods :item="item"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        queryObj: {
          query: '',
          cid: '',
          pagenum: 1,
          pagesize: 10
        },
        goodsList: [],
        total: 0,
        // 节流阀
        isLoading: false

        
      }
    },
    onLoad(options) {
      // console.log(options)
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      // 获取商品列表的处理函数
      this.getGoodsList()
    },
    methods: {
      async getGoodsList(cb) {
        // 打开节流阀
        this.isLoading = true
        const {data: res} = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        // 关闭节流阀
        this.isLoading = false
        
        // 只要数据请求完毕,就立即按需调用 cb 回调函数
        cb && cb()
        if(res.meta.status !== 200) return uni.$showMessage()
        // this.goodsList = res.message.goods
        // this.total = res.message.total
        // console.log(res)
        // 为商品列表赋值，进行新旧数据的拼接
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
      },
      gotoDetail(item) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      }
    },
    onReachBottom() {
      // 判断是还有下一页数据
      if(this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return
      
      // 判断是否正在发起请求,如果是则不放弃额外的请求
      if(this.isLoading) return
      // 页码自动 +1
      this.queryObj.pagenum += 1  // 重新获取商品列表
      this.getGoodsList()
    },
    onPullDownRefresh() {
      // 重置关键数据
      this.queryObj.pagenum = 1,
      this.total = 0
      this.isLoading = false
      this.goodsList = []
      
      // 重新发起请求
      this.getGoodsList(() => {uni.stopPullDownRefresh()})
    }
  }
</script>

<style lang="scss">

</style>
